<?php

	error_reporting(E_ALL ^ E_NOTICE);
	ini_set('display_errors', '1');
	ini_set('memory_limit', '300M');	
	include_once('./config.php');
	include_once('api/classes/gbif.processor.php');

	$success = true;
	
	switch( $_REQUEST['cmd'] ) {
		case 'formSubmitted':
			# creating pickup directory if not present
			if(!file_exists($pickUpPath)) {
				@mkdir($pickUpPath,0775);
			}
			
			$pickupJson = json_encode(array('status' => false));

			$allowedExtensions = array("xls", "xlsx");
			if (is_array($_FILES)) {			
			foreach ($_FILES as $file) {
				$i++;
				if ($file['tmp_name'] > '') {
					if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) {
						$errorMsg = $file['name'] . " is an invalid file type!";
						$success = false;
						break;
					} else {
						// Valid File Do something with it.
						$conversionID = uniqid();
						mkdir($pickUpPath . $conversionID);
						$uploaddir = $pickUpPath . $conversionID . "/";
						$uploadfile = $conversionID . "-" . $i . "." . end(explode(".", strtolower($file['name'])));

						if (move_uploaded_file($file['tmp_name'], $uploaddir . $uploadfile)) {

							include_once("api/classes/gbif.general.php");
							include_once("api/classes/gbif.eml.php");
							$general = new General($uploaddir . $uploadfile);
							$sheetType = $general->getVersion();
							unset($general);

							$allowedTypes = array('Checklist-1_v1', 'Checklist-2_v1', 'Checklist-3_v1', 'Occurrence-1_v1', 'Metadata-1_v1');
							$oldTypes = array('Checklist-1_v0.9', 'Checklist-2_v0.9', 'Checklist-3_v0.9', 'Occurrence-1_v0.9', 'Metadata-1_v0.9');
							if (in_array($sheetType, $allowedTypes)) {
								$response = process($sheetType, $uploadfile, $uploaddir, $conversionID );
								$response["pickupFile"] = str_replace($basePath, $baseUri, $response["pickupFile"]);
								switch($sheetType) {
									default:										
										$filename = "dwcarchive.zip";
										break;
									case "Metadata-1_v1":
										$filename = "eml.xml";
										break;	
								}

								$errorMsg = "EML Errors:";
								if (count($response["errors"]->eml["errors"])) {
									foreach($response["errors"]->eml["errors"] as $error) {
										$errorMsg .= "<br>" . $error["variable"] . ": " . $error["msg"];
									}
									$success = false;				
								}
							} elseif (in_array($sheetType, $oldTypes)) {
								$errorMsg = $file['name'] . " is an outdated spreadsheet template. Please use the latest version. We are sorry for the inconvenience.";
								$success = false;
							} else {
								$errorMsg = $file['name'] . " is not a valid spreadsheet template!";
								$success = false;				
							}
/*							
							if ($response["errors"] != "") {
								$errorMsg = $file['name'] . " is an invalid file type!";
								$success = false;				
							}
*/							
						}
					}
				}
			}
			}
			break;
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
	  <meta name="copyright" lang="en" content="GBIF" />
    <meta name="description" content="The spreadsheet processor is a web application that transforms that transforms pre-configured MS Excel spreadsheet files to a GBIF-supported standard data format called a Darwin Core Archive file. The pre-configured Excel files contain multiple worksheets that support data entry. One worksheet supports the GBIF metadata profile. A second worksheet supports the publication of either primary biodiversity data, in the form of natural history collections /species observational data or basic species checklists. The spreadsheet processor accepts completed spreadsheet files via a web-form or as an email attachment. The processor performs a series of data validation and transformation steps and returns a validated Darwin Core Archive file to the user that can be published via GBIF or other biodiversity networks that support this format." />
    <meta name="keywords" content="gbif, dwca, Darwin Core Archive Spreadsheet Processor, excel, darwin core, darwin core archive, archive, template" />    
 		<link rel="stylesheet" type="text/css" href="resources/css/style.css"/>		
		<title>Darwin Core Archive Spreadsheet Processor</title>
 	</head>
 	<body>
		<div id="wrapper">
      <div id="topmenu">
      <div class="beta">
        <img src="resources/images/beta-stamp.gif" alt="DwC-A Spreadsheet Processor is still in beta." width="124" height="74" border="0">
      </div>
      <ul>
        <li class="current"><a href="http://www.gbif.org">home
        </a></li>
        <!--li><a href="about.html">about</a></li-->
        <li><a href="http://tools.gbif.org/">tools</a></li>
      </ul>
      <br /><br />
      <div class="language">
      <span>Language: </span>
      <select name="language" size="1" onChange="window.location.href = 'index' + this.value + '.php';">
        <option selected="selected" value="">English</option>
        <option value="-es">Spanish</option>
        <option value="-fr">French</option>
      </select>
      </div>
    </div>

			<div id="logo"> <a href="http://www.gbif.org"><img src="resources/images/gbif.jpg" alt="GBIF" border="0" align="left" style="padding: 0 30px 0 5px"></a>
			<br><div style="font-size: 12px; color: #AAA"><p style="margin-bottom: 0px; font-size: 16px; font-weight: bold;">free and open access to biodiversity data</p>
			  <p style="margin-top: 5px; font-size: 18px; font-weight: bold;">Darwin Core Archive Spreadsheet Processor</p></div>
			</div>
			<div id="content">			

<div style="float: right; padding: 8px; border: dashed thin #999; -moz-border-radius: 5px; border-radius: 5px;">
    	<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
			<p>
				<label>Upload File:<br>
					<input type="file" name="occurance" id="occurance" />
				</label>
			</p>
			<p>
				<label>
					<img src="resources/images/stamp.jpg" width="68" height="70" align="right" style="padding-top:10px">
					<input type="submit" name="button" id="button" value="Process File" />
				</label>
				<input name="cmd" type="hidden" id="cmd" value="formSubmitted" />
			</p>
			<p>or</p>
			<p>mail to:  <a href="mailto:spreadsheets@tools.gbif.org">spreadsheets@tools.gbif.org</a></p>
      </form>
	</div>
<?php
	if ($success && $response["pickupFile"] != '') {
		print '<div class="response">';
		switch($sheetType) {
			default:										
				print "Your Darwin Core Archive has been created.&nbsp;&nbsp;&nbsp; <a href=\"" . $response["pickupFile"] . "\">Click to Download Archive.</a>";
				break;
			case "Metadata-1_v1":
				print "Your EML Metadata file has been created.&nbsp;&nbsp;&nbsp; <a href=\"" . $response["pickupFile"] . "\">Click to Download Metadata file.</a>";
				break;	
		}
		print '</div>';
	}
	
	if (!$success) {
		print '<div class="response">';
		print "<p style='color: red'>Some errors have occured:</p><br>$errorMsg<br>";
		if ($response["pickupFile"] != '') {
			print "<br>You may <a href=\"" . $response["pickupFile"] . "\">download your archive</a> but it may contain some errors for submission to GBIF.</p>";
		}
		print '</div>';
	}
?>

<p><strong>Directions:</strong></p>
<ol>
  <li>Review the available spreadsheet templates</li>
  <li>Download and complete the templates according to the user guidelines</li>
  <li>Click the "Choose File" button on the right to upload the completed spreadsheet or</li>
  <li>Email it to <a href="mailto:spreadsheets@tools.gbif.org">spreadsheets@tools.gbif.org</a></li>
  <li>Receive a validated Darwin Core Archive file or EML metadata document.</li>
  <li>To publish, put the Darwin Core Archive file and EML metadata document online, with a stable URL.</li>
  <li>Follow the <a href="http://www.gbif.org/informatics/standards-and-tools/publishing-data/registration/" target="_blank">GBIF data registration guidelines</a> to register the data files with GBIFS.</li>
  </ol>
<p><strong>Note</strong>:&nbsp; The processor does NOT publish a datafile to GBIF.&nbsp; It provides a publication-ready file. </p>
<p>Available Spreadsheet Templates &ndash; The processor currently only supports a set of pre-configured spreadsheet &lsquo;template&rsquo; files.&nbsp; Each is available in the older XLS format and the new XLSX format, which supports more than 64,000 rows.</p>
<h1><strong><br>
  The following templates are available:</strong></h1>
<img src="resources/images/excel-icon.jpg" alt="Templates" width="82" height="84" align="left" style="padding-right:10px; padding-bottom: 155px;"><ul>
  <li><a href="templates/metadata/metadata-1_v1.xls"><strong>Metadata</strong></a> - Use this template to describe a database or other data resource.&nbsp; Processor output is an Ecological Metadata Language Document that conforms to a GBIF metadata profile. [<a href="templates/metadata/metadata-1_v1.xlsx">XLSX format</a>]</li>
  </ul>
<p><a href="templates/occurrence/occurrence-1_v1.xls"><strong>Species Occurrence</strong></a> - Use this template to record or store basic species collections or observational data. [<a href="templates/occurrence/occurrence-1_v1.xlsx">XLSX format</a>]</p>
<p><strong><br>
  Species Checklists</strong> &ndash; These templates provide different methods for recording and storing simple annotated species checklists.&nbsp;&nbsp; The different versions offer different methods for recording classification information.<br> 
  <hr align="center" size="1" noshade>
</p>
<p><a href="templates/checklist/checklist-1_v1.xls"><strong>Checklist 1</strong></a> - Supports a &lsquo;normalised&rsquo; classification where the classification is stored in two spreadsheet columns: one stores the ID of the taxon and another stores the ID of the parent taxon. [<a href="templates/checklist/checklist-1_v1.xlsx">XLSX format</a>]<br>
</p>
<ul>
  <li><a href="templates/checklist/checklist-2_v1.xls"><strong>Checklist 2</strong></a> - Classification in columns where the user can define the specific higher taxon groups.&nbsp;&nbsp; Useful when using super- or sub- ranks or other ranks outside the core Linnaean ranks. [<a href="templates/checklist/checklist-2_v1.xlsx">XLSX format</a>]<br>
  </li>
  <li></li>
  </ul>
<ul>
  <li><a href="templates/checklist/checklist-3_v1.xls"><strong>Checklist 3</strong></a> - Classification in columns is limited to the basic Linnaean ranks of Kingdom, Phylum, Class, Order, Family, Genus, etc. [<a href="templates/checklist/checklist-3_v1.xlsx">XLSX format</a>]</li>
</ul>
<p><br>
  <img src="resources/images/info.jpg" width="22" height="22" align="absmiddle"> Project Website and additional documentation <a href="http://code.google.com/p/gbif-spreadsheet-processor/" target="_blank">http://code.google.com/p/gbif-spreadsheet-processor/</a></p>
</div>
  <div id="footer">
	  <?php include_once("/var/www/html/tools/footer.php"); ?>
  </div>
		</div>
	<script type="text/javascript">
   var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
   document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  </script>
  <script type="text/javascript">
   var pageTracker = _gat._getTracker("UA-18593842-1");
   pageTracker._initData();
   pageTracker._trackPageview();
  </script>    
	</body>
</html>